window.onload = function () {
    setInterval(changeColor, 250);
    listProducts();
    checkLogin();
}

function getRandomColor() {
    const h = Math.floor(Math.random() * 360);
    const s = Math.floor(Math.random() * 40) + 50;
    const l = Math.floor(Math.random() * 40) + 50;

    return 'hsl(' + h + ', ' + s + '%, ' + l + '%)';
}

function changeColor() {
    var accountButton = document.getElementsByClassName("account");
    var color = getRandomColor();
    for (var i = 0; i < accountButton.length; i++) {
        accountButton[i].style.color = color;
    }
}

function listProducts() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://localhost:8080/listProducts", true);

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                showProducts(xhr.responseText);
            }
            else {
                console.error(xhr.status);
            }
        }
    }

    xhr.send();
}

function showProducts(json) {
    var products = JSON.parse(json);
    const list = document.getElementsByClassName("list")[0];
    let product;
    for (let i = 0; i < products.length; i++) {
        product = document.createElement("a");
        product.href = "content.jsp?id=" + products[i].id;
        product.innerHTML = "<div class='product'><img src='img/" + products[i].img + "'>"
            + "<div class='title'>" + products[i].name + "</div>"
            + "<div class='price'>￥" + products[i].price + "</div>"
            + "<div class='sales'>月销量" + products[i].sales + "</div>"
            + "</div>";
        list.appendChild(product);
    }
}

function checkLogin() {
    var username = getUserNameFromCookie();

    if (username != null) {
        var login = document.querySelectorAll('.account');

        //删除所有带account的对象
        login.forEach(function (item) {
            item.parentNode.remove();
        });
        var li = document.createElement('li');
        var login = document.createElement('a');

        login.innerHTML = username;
        login.href = '#';
        login.addEventListener('click', logOut);
        login.setAttribute('class', 'account');

        li.appendChild(login);
        document.querySelectorAll('ul')[0].appendChild(li);
    }
}

function logOut() {
    var confirm = window.confirm('确定要退出登录吗？');
    if (!confirm) {
        return;
    }
    var cookies = document.cookie.split(';');

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i].trim();

        if (cookie.startsWith('login=')) {
            document.cookie = cookie + ";expires=" + new Date(0).toUTCString();
        }
    }

    location.reload();
}